window.genesis || (window.genesis = {});

(function ($) {
    genesis.required("/module/post");

    var _WIN = window;
    var _PARENT = _WIN.parent;

    var funs;
    if(_WIN != _PARENT) {
        do {
            _WIN = _PARENT;
            _PARENT = _WIN.parent;
        } while (_PARENT != _WIN);


        var showCaptcha = _WIN.genesis["showCaptcha"];
        var hideCaptcha = _WIN.genesis["hideCaptcha"];
        funs = (showCaptcha && hideCaptcha) ? {"showCaptcha": showCaptcha, "hideCaptcha": hideCaptcha} : null;
    }

    funs = funs || (function () {
            var html =
                '<div>\
                    <form class="form-inline ">\
                        <div class="message" style="color: #a94442;"></div>\
                        <div>\
                            <input type="text" style="display: inline-block" placeholder="请输入验证码"/>\
                            <img src="" style="display: inline-block" style="width: 80px;"/>\
                        </div>\
                    </form>\
                </div>';
            var options = {};
        return {
            showCaptcha: function (prms, cb) {
                var $m;
                if(!options["modal"]) {
                    $m = $(html).appendTo("body");
                    options["modal"] = $m;
                }else {
                    $m = options["modal"];
                }

                var handler = function () {
                    var code = $(":text", $m).val();
                    cb && cb(code);
                    return false;
                };

                $m.find("form").on("submit", handler);

                $(".message", $m).text(prms.message || "");
                $(":text", $m).focus().val("");
                $("img", $m).attr("src", prms.url + "/captcha?" + new Date().getTime());
                $m.find("input").focus();


                $m.dialog({
                    title: '操作确认',
                    width: 300,
                    height: 150,
                    modal: true,
                    buttons: [{
                        text: '确定',
                        "handler": handler
                    }, {
                        text: '关闭',
                        "handler": function () {
                            $m.dialog("close");
                        }
                    }]
                });
            },
            hideCaptcha: function (cb) {
                var  $m = options["modal"];
                if(!$m) {
                    return;
                }
                $m.off("hidden.bs.modal").on("hidden.bs.modal", function(){
                    $m.off("hidden.bs.modal");
                    cb && cb();
                });
                $m.dialog("close");
            }
        }
    })();
    
    window.genesis = $.extend(window.genesis, funs);
})(jQuery);